<template>
	<view class="index">
		<!-- v-bind:markers="markers" -->
		<map id="myMap" v-bind:latitude="location.latitude" :markers="markers" v-bind:longitude="location.longitude"
			:show-location="true" :polyline="polyline"></map>
		<view class="list" v-if="orders.length!=0 && item.describe && !receivingOrder && !haveOrder"
			@click="confirmReceivingOrders(item)" v-for="(item,index) in orders" :key="index">
			<view class="item">
				<view class="text">
					<view class="orderId">
						订单ID：{{item.orderId}}
					</view>
					<view class="get-in-car">
						乘客上车点：{{item.describe}}
					</view>

				</view>
			</view>
		</view>

		<view class="get-order">
			<view class="button" v-if="!receivingOrder && !haveOrder">
				<button type="primary" style="background-color: #58f;" @click="getNearbyOrder">获取附近订单</button>
			</view>
			<view class="info" v-if="haveOrder && !isArriveGetInCarFlag">
				行程距离：{{distancePassenger}} 时间：{{durationPassenger}}
			</view>
			<view class="info" v-if="haveOrder && !isArriveGetInCarFlag">
				距离乘客：{{toPassengerDistance}}Km
			</view>


			<view class="info" v-if="isGetInCar">
				行程距离：{{distance}} 时间：{{duration}}
			</view>
			<view class="info">
				<view class="where">
					当前位置：
					<view class="address">
						<text>{{location.address}}</text>
						<text>{{location.name}}</text>
					</view>

				</view>
				<view class="profile" @click="toDriverInfo">
					司机信息
				</view>

			</view>
			<view class="button" v-if="isArriveGetInCarFlag  && !isGetInCar">
				<button type="primary" style="width: 100%;background-color: #58f;" @click="GetOnTheCar">乘客上车</button>
			</view>
			<view class="button" v-if="(haveOrder || receivingOrder) && !order.driverId">
				<button type="primary" style="width: 100%;background-color: #58f;" @click="orderOver">取消订单</button>
			</view>
			<view class="button" v-if="order.driverId">
				<button type="primary" style="width: 100%;background-color: #58f;" @click="orderOver">订单结束</button>
			</view>
		</view>
	</view>
</template>

<script>
	import amapFile from '@/libs/amap-wx.js';
	import utils from "../../common/utils.js";
	const api = utils.websiteUrl;
	export default {
		data() {
			return {
				myAmapFun: undefined,
				location: {
					name: '',
					address: '',
					longitude: 0,
					latitude: 0
				},
				//定义经纬度
				// longitude: '',
				// latitude: '',
				markers: [],
				//存放乘客目的地
				target: {},
				// 存放乘客起点
				start: {},
				token: '',
				// 选择的订单信息
				order: {},
				// 所有订单
				orders: [],
				// 乘客用户名
				userName: '',
				// 用户起始和目的地
				passenger: {},
				// 乘客是否上车标记
				isGetInCar: false,
				// 乘客Id
				passagerId: undefined,
				// 结束订单信息，暂存
				orderOverInfo: {},
				// 暂存逆地址编码信息
				describe: {},
				// 是否接单
				receivingOrder: false,
				// 司机是否存在进行中的订单
				haveOrder: false,
				// 路径规划
				polyline: [],
				// 乘客打车距离
				distance: "",
				// 打车时间
				duration: "",
				// 距离乘客直线距离
				toPassengerDistance: 0,
				// 距离乘客距离
				distancePassenger: 0,
				// 距离乘客时间
				durationPassenger: 0,
				// 判断是否到达上车点标记
				isArriveGetInCarFlag: false,
				// 乘客手机号后四位
				phoneNumber: ''





			}
		},
		onLoad() {
			//2.创建实例对象，以便于后面调用它的方式，实现相关功能
			//传入自己的key
			this.myAmapFun = new amapFile.AMapWX({
				key: '85208405250c458368d44bccd8104998'
			});

			//3.调用方法获取位置信息(可以封装成一个函数)
			//在加载时调用位置信息

			// this.forGetNearbyOrder();
			this.token = uni.getStorageSync('token')
			this.getDriverOrderWhenUse()




		},
		onShow() {

		},
		methods: {
			// 前往司机个人信息
			toDriverInfo() {
				let that = this;
				uni.redirectTo({
					url: "/pages/driver_info/driver_info",
					success: () => {
						console.log('success to driver profile')
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			getLocation() {
				const that = this;
				//调用方法获取位置信息
				return new Promise((resolve, reject) => {
					this.myAmapFun.getRegeo({
						//成功的回调函数(获取位置信息成功)
						success: (res) => {
							console.log('当前位置信息', res);
							this.location.name = res[0].desc;
							this.location.longitude = res[0].longitude;
							this.location.latitude = res[0].latitude;
							console.log(res[0].desc);
							console.log(this.location)
							resolve("suc")
						},
						//失败的回调函数(获取位置信息失败)
						fail: (err) => {
							console.log('获取位置失败0', err);
							reject("rej:" + err)
						}
					})
				})
			},
			// 获取附近打车订单
			getNearbyOrder() {
				let that = this;
				uni.request({
					url: api + "order/getNearbyOrder",
					method: "GET",
					sslVerify: false,
					data: {
						positionLatitude: that.location.latitude,
						positionLongitude: that.location.longitude
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						"token": that.token
					},
					success: (res) => {
						console.log('获取附近订单')
						console.log(res)
						if (res.data.code == '0' && res.data.data.length != 0) {
							console.log(res.data.data)
							that.orders = res.data.data

							that.useDescribe()
						} else {
							uni.showToast({
								duration: 1000,
								title: "附近没有订单",
								icon: 'error'
							})
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			// 间隔时间获取订单
			forGetNearbyOrder() {
				let that = this;
				setInterval(function() {
					that.getNearbyOrder();
				}, 1000)
			},
			// 获取司机的进行中订单(司机)
			getDriverOrder() {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.request({
						url: api + 'order/getDriverOrder',
						method: "GET",
						sslVerify: false,
						data: {

						},
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
							"token": that.token
						},
						success: (res) => {
							console.log("获取司机的进行中订单(司机)")
							console.log(res)
							if (res.data.code == '0') {
								if (res.data.data.dricerId) {
									that.haveOrder = true
								}

								that.start.latitude = res.data.data.positionStartLatitude
								that.start.longitude = res.data.data.positionStartLongitude

								that.target.latitude = res.data.data.positionEndLatitude
								that.target.longitude = res.data.data.positionEndLongitude

								that.order.driverId = res.data.data.dricerId
								that.order.passengerId = res.data.data.passengerId
								that.order.beginTime = res.data.data.beginTime
								that.order.orderId = res.data.data.orderId
								that.order.state = res.data.data.state

								that.markers = []
								let start1 = {
									id: 0,
									latitude: that.start.latitude,
									longitude: that.start.longitude,
									iconPath: "../../static/起点.png",
									width: 40,
									height: 40
								}

								let end1 = {
									id: 1,
									latitude: that.target.latitude,
									longitude: that.target.longitude,
									iconPath: "../../static/终点.png",
									width: 40,
									height: 40
								}
								that.markers.push(start1)
								that.markers.push(end1)


								// uni.redirectTo({
								// 	url: '/pages/index_driver/index_driver'
								// })

							}
							if (res.data.code == '1') {
								that.haveOrder = false
								uni.showToast({
									duration: 1000,
									title: "没有进行中订单",
									position: 'center',
									icon: 'error'
								})
							}
							resolve("suc")
						},
						fail: (err) => {
							that.haveOrder = false
							console.log(err).
							reject("rej:" + err)

						}
					})
				})
			},
			// 乘客上车
			GetOnTheCar() {
				let that = this;
				uni.showModal({
					title: "输入乘客手机号后四位",
					showCancel: true,
					cancelColor: "#0f80ff",
					confirmColor: "#0f80ff",
					editable: true,
					placeholderText: '手机号后四位',
					success: (res) => {
						if (res.confirm) {

							that.phoneNumber = res.content
							console.log("乘客上车")
							uni.request({
								url: api + 'order/GetOnTheCar',
								sslVerify: false,
								method: 'GET',
								data: {
									orderId: that.order.orderId,
									userName: that.phoneNumber
								},
								header: {
									'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
									"token": that.token
								},
								success: (res) => {
									console.log(res)
									if (res.data.code == '0') {
										console.log('上车成功')
										that.isGetInCar = true
										that.markers = []
										let start1 = {
											id: 0,
											latitude: that.start.latitude,
											longitude: that.start.longitude,
											iconPath: "../../static/起点.png",
											width: 40,
											height: 40
										}

										let end1 = {
											id: 1,
											latitude: that.target.latitude,
											longitude: that.target.longitude,
											iconPath: "../../static/终点.png",
											width: 40,
											height: 40
										}
										that.markers.push(start1)
										that.markers.push(end1)
										let start = this.location.longitude + ',' + this.location
											.latitude
										let end = this.target.longitude + ',' + this.target
											.latitude
										that.getPlanningRoute(start, end, 10)
									}
									if (res.data.code == '1') {
										console.log('上车失败')
										that.isGetInCar = false
									}
								},
								fail: (err) => {
									console.log('上车请求失败')
									console.log(err)
								}
							})


						} else if (res.cancel) {
							console.log("取消乘客上车")
						}
					}
				})
			},
			// 确认接单提示
			confirmReceivingOrders(order) {
				let that = this
				uni.showModal({
					title: "确认接单",
					showCancel: true,
					cancelColor: "#0f80ff",
					confirmColor: "#0f80ff",

					success: (res) => {
						if (res.confirm) {

							console.log("确认接单")
							that.ReceivingOrders(order)

						} else if (res.cancel) {
							console.log("取消接单")
						}
					},
					fail: (err) => {
						console.log("确认接单 弹出框失败")
					}
				})
			},
			// 接单
			ReceivingOrders(order) {
				let that = this;
				uni.request({
					url: api + 'order/ReceivingOrders',
					sslVerify: false,
					method: 'GET',
					data: {
						orderId: order.orderId
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						"token": that.token
					},
					success: (res) => {
						console.log(res)
						if (res.data.code == '0') {
							that.order = res.data.data
							that.receivingOrder = true
							console.log('接单成功')
							console.log(res)

							uni.reLaunch({
								url: "/pages/index_driver/index_driver"
							})

						}
					},
					fail: (err) => {
						that.receivingOrder = false
						console.log('接单失败')
					}
				})
			},
			// 订单结束
			orderOver() {
				let that = this;
				uni.request({
					url: api + 'order/orderOver',
					method: 'GET',
					sslVerify: false,
					data: {
						positionLatitude: that.location.latitude,
						positionLongitude: that.location.longitude,
						orderId: that.order.orderId
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						"token": that.token
					},
					success: (res) => {
						console.log('订单成功结束')
						if (res.data.code == '0') {
							that.orderOverInfo = res.data.data
						}
						uni.showToast({
							duration: 1000,
							title: "订单结束",
							position: 'center',
						})
						uni.reLaunch({
							url: '/pages/index_driver/index_driver'
						})
					},
					fail: (err) => {
						console.log('订单结束失败')
						console.log(err)
					}
				})
			},
			// 调用逆地址编码获取信息
			async useDescribe() {
				let that = this
				for (var i = 0; i < that.orders.length; i++) {
					await that.getDescribe(that.orders[i], i);
					console.log("调用逆地址编码获取信息")

					// console.log(this.describe.formatted_address)
					// that.orders[i]['describe'] = res.formatted_address
					// console.log(that.orders[i]['describe'])
				}

			},
			// 逆地址编码
			getDescribe(item, i) {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.request({

						url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
						methods: 'GET',
						sslVerify: false,
						data: {
							key: '87ae0042dce7c543b9be96be129ea404',
							location: String(Number(item.positionStart.positionLatitude).toFixed(6)) +
								',' + String(
									Number(item.positionStart.positionLongitude).toFixed(6)),
							extensions: 'all'
						},
						success: (res) => {
							console.log("逆地址编码")
							console.log(res)
							if (res.data.status == 1) {
								that.describe = res.data.regeocode
								that.orders[i]['describe'] = that.describe.formatted_address
							}
							resolve("suc")
						},
						fail: (err) => {
							console.log("逆地址编码失败")
							console.log(err)
							reject("rej:" + err)
						}

					})
				})

			},
			// 规划路径
			getPlanningRoute(start, end, strategy = 10) {
				let that = this
				uni.showLoading({
					title: '加载中'
				});
				that.myAmapFun.getDrivingRoute({
					origin: start,
					destination: end,
					strategy: strategy, //备选方案
					success: function(data) {
						// console.log('所有路径',data)
						if (data.paths && data.paths[0] && data.paths[0].steps) {
							// 默认 10 会 对返回多条路径的方案  按照时间短的
							let goodRouter = data.paths.sort((a, b) => {
								return a.duration - b.duration
							})[0]

							that.distance = (goodRouter.distance * 0.001).toFixed(2) + '公里'
							that.duration = '大约' + (goodRouter.duration / 60).toFixed(2) + '分钟'

							let steps = goodRouter.steps
							let points = []
							for (var i = 0; i < steps.length; i++) {
								var poLen = steps[i].polyline.split(';');
								for (var j = 0; j < poLen.length; j++) {
									points.push({
										longitude: parseFloat(poLen[j].split(',')[0]),
										latitude: parseFloat(poLen[j].split(',')[1])
									})
								}
							}
							that.polyline = [{
								points: points,
								color: strategy === 10 ? '#43e5e5' : strategy === 2 ? '#0742d9' :
									'#ee6b06',
								width: 8,
							}]
						}
						uni.hideLoading();
					},
					fail: function(info) { //失败回调
						console.log('路线规划失败')
						console.log(info)
						uni.hideLoading();
						uni.showToast({
							title: '路线规划失败',
							icon: 'error'
						});
					},
				})
			},
			// 前往乘客规划路径
			getPlanningRoutePassenger(start, end, strategy = 10) {
				let that = this
				uni.showLoading({
					title: '加载中'
				});
				that.myAmapFun.getDrivingRoute({
					origin: start,
					destination: end,
					strategy: strategy, //备选方案
					success: function(data) {
						// console.log('所有路径',data)
						if (data.paths && data.paths[0] && data.paths[0].steps) {
							// 默认 10 会 对返回多条路径的方案  按照时间短的
							let goodRouter = data.paths.sort((a, b) => {
								return a.duration - b.duration
							})[0]

							that.distancePassenger = (goodRouter.distance * 0.001).toFixed(2) + '公里'
							that.durationPassenger = '大约' + (goodRouter.duration / 60).toFixed(2) + '分钟'

							let steps = goodRouter.steps
							let points = []
							for (var i = 0; i < steps.length; i++) {
								var poLen = steps[i].polyline.split(';');
								for (var j = 0; j < poLen.length; j++) {
									points.push({
										longitude: parseFloat(poLen[j].split(',')[0]),
										latitude: parseFloat(poLen[j].split(',')[1])
									})
								}
							}
							that.polyline = [{
								points: points,
								color: strategy === 10 ? '#43e5e5' : strategy === 2 ? '#0742d9' :
									'#ee6b06',
								width: 8,
							}]
						}
						uni.hideLoading();
					},
					fail: function(info) { //失败回调
						console.log('路线规划失败')
						console.log(info)
						uni.hideLoading();
						uni.showToast({
							title: '路线规划失败',
							icon: 'error'
						});
					},
				})
			},
			// 司机接单后前往乘客起点
			toPassenger() {
				let that = this;

				var start = that.location.longitude + ',' + that.location.latitude
				var end = that.start.longitude + ',' + that.start.latitude
				console.log(start, end)
				this.getPlanningRoutePassenger(start, end, 10)
			},
			// 计算两点之间直线距离
			calculateDistance(lat1, lon1, lat2, lon2) {


				var Lat1 = lat1 * Math.PI / 180.0;
				var Lat2 = lat2 * Math.PI / 180.0;
				var Lat3 = Lat1 - Lat2;
				var Lb3 = lon1 * Math.PI / 180.0 - lon2 * Math.PI / 180.0;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(Lat3 / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) *
					Math.pow(Math.sin(Lb3 / 2), 2)));
				s = s * 6378.137; //地球半径
				s = Math.round(s * 10000) / 10000;
				console.log(s)
				return s



			},
			// 判断司机是否到达上车点
			isArriveGetInCar() {
				let that = this;
				var distance;
				var lat1 = that.location.latitude
				var lon1 = that.location.longitude
				var lat2 = that.start.latitude
				var lon2 = that.start.longitude

				var start = that.location.longitude + ',' + that.location.latitude
				var end = that.start.longitude + ',' + that.start.latitude
				that.getPlanningRoutePassenger(start, end, 10)
				distance = that.calculateDistance(lat1, lon1, lat2, lon2)
				this.toPassengerDistance = distance

				var timer = setInterval(function() {
					that.getLocation();
					lat1 = that.location.latitude
					lon1 = that.location.longitude
					lat2 = that.start.latitude
					lon2 = that.start.longitude

					start = that.location.longitude + ',' + that.location.latitude
					end = that.start.longitude + ',' + that.start.latitude

					that.getPlanningRoutePassenger(start, end, 10)
					distance = that.calculateDistance(lat1, lon1, lat2, lon2)
					this.toPassengerDistance = distance
					that.isArriveGetInCarFlag = false
				}, 5000)
				if (distance * 1000 < 5 || that.order.driverId) {
					that.isArriveGetInCarFlag = true
					if (that.order.driverId) {
						uni.showToast({
							duration: 1000,
							title: "您已有进行中的订单",
							icon: 'success',
						})
					} else {
						uni.showToast({
							duration: 1000,
							title: "您已到达上车点附近",
							icon: 'success',
						})
					}

					clearInterval(timer)
				}
			},
			// 同步获取司机进行中的订单
			async getDriverOrderWhenUse() {
				let that = this;
				await this.getLocation();
				await this.getDriverOrder()
				console.log("同步获取司机进行中的订单")

				if (this.haveOrder) {

					var start = this.start.longitude + ',' + this.start.latitude
					var end = this.target.longitude + ',' + this.target.latitude

					console.log('存在订单')

					var lat1 = this.location.latitude
					var lon1 = this.location.longitude

					var lat2 = Number(this.start.latitude)
					var lon2 = Number(this.start.longitude)
					console.log(lat1, lon1, lat2, lon2)
					this.toPassengerDistance = this.calculateDistance(lat1, lon1, lat2, lon2)
					// this.toPassenger()

					this.isArriveGetInCar()
				}

				if (this.order.driverId) {
					that.markers = []
					let start1 = {
						id: 0,
						latitude: that.start.latitude,
						longitude: that.start.longitude,
						iconPath: "../../static/起点.png",
						width: 40,
						height: 40
					}

					let end1 = {
						id: 1,
						latitude: that.target.latitude,
						longitude: that.target.longitude,
						iconPath: "../../static/终点.png",
						width: 40,
						height: 40
					}
					that.markers.push(start1)
					that.markers.push(end1)
					let start = this.location.longitude + ',' + this.location
						.latitude
					let end = this.target.longitude + ',' + this.target
						.latitude
					this.getPlanningRoute(start, end, 10)
				}

			},
			// 判断是否到达终点
			isArriveTarget() {
				var lat1 = this.location.latitude
				var lon1 = this.location.longitude
				var lat2 = this.target.latitude
				var lon2 = this.target.longitude
				var distance = this.calculateDistance(lat1, lon1, lat2, lon2)
				if (distance * 1000 < 5) {
					您已到达
				}
			}



		}
	}
</script>

<style lang="scss">
	.index {
		width: 100vw;
		height: 100vh;

		//地图
		#myMap {
			width: 100vw;
			height: 100vh;
		}

		.list {
			width: 98vw;
			background-color: #fff;
			//固定定位
			position: fixed;
			left: 1vw;
			bottom: 90vh;
			max-height: 50vh;
			box-shadow: 1px 1px 4px 4px #ccc;
			// .list {
			// 	height: calc(100%-120rpx);
			overflow: scroll;

			// }
			.get-in-car {
				font-size: 13px;
			}

			.orderId {
				font-size: 13px;
			}
		}

		.item {
			height: 150rpx;
			border-bottom: 1px solid #eee;
			display: flex;
			align-items: center;
		}

		.get-order {
			width: 98vw;
			background-color: #fff;
			//固定定位
			position: fixed;
			left: 1vw;
			bottom: 5vw;
			box-shadow: 1px 1px 4px 4px #ccc;


			.info {
				.where {
					width: 50%;
					height: 100rpx;
					// line-height: 100rpx;
					background-color: #fff;
					border-right: solid #eee;
					line-height: 50rpx;

					.address {

						font-size: 15px;
					}
				}

				.profile {
					height: 100rpx;
					border: 1px solid #eee;
					// display: flex;
					// padding: 0 40rpx;
					align-items: center;
					text-align: center;
					line-height: 100rpx;
					width: 50%;
				}

				display: flex;
				align-content: space-around;


			}
		}

	}
</style>